package com.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.model.auto.*;
import com.model.auto.req.*;
import com.model.auto.resp.*;
import com.service.IMendaoStuService;
import com.service.IMendaoTestReportService;
import com.service.IMendaoTestService;
import com.service.IMendaoTopicLibraryService;
import com.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 门道测评V2
 * @author zhaoyifan
 * @date 2024/5/17 10:39
 */
@RestController
@RequestMapping("/mendao/v2")
@Slf4j
public class MendaoTestV2Controller extends BaseController{

    @Autowired
    private IMendaoTopicLibraryService topicLibraryService;
    @Autowired
    private IMendaoTestService mendaoTestService;
    @Autowired
    private IMendaoTestReportService testReportService;
    @Autowired
    private IMendaoStuService mendaoStuService;

    /**
     * 获取测评
     *
     * @param type type=1后台获取全部type=2前台获取列表
     * @return
     */
    @GetMapping(value = "/getTest")
    public R getTest(Integer type) {
        try {
            List<MendaoTestResp> respList = new ArrayList<MendaoTestResp>();
            //type=1后台获取全部type=2前台获取列表
            List<MendaoTest> list = mendaoTestService.getList(type);
            if (list != null && list.size() > 0) {
                for (MendaoTest test : list) {
                    MendaoTestResp mendaoTestResp = new MendaoTestResp();
                    mendaoTestResp.setTestId(test.getId());
                    mendaoTestResp.setTestName(test.getName());
                    mendaoTestResp.setTestImage(test.getImage());
                    mendaoTestResp.setTestIntroduction(test.getIntroduction());
                    mendaoTestResp.setTestDesc(test.getTestDesc());
                    mendaoTestResp.setStatus(test.getStatus());
                    mendaoTestResp.setQuestionsNum(test.getQuestionsNum());
                    mendaoTestResp.setTotalTime(test.getTotalTime());
                    mendaoTestResp.setStatus(test.getStatus());
                    respList.add(mendaoTestResp);
                }
            }
            return R.ok(respList);
        } catch (Exception e) {
            log.error("获取测评异常", e);
            return R.error("发生异常");
        }
    }

    /**
     * 根据id获取测评
     *
     * @param testId
     * @return
     */
    @GetMapping(value = "/getTestById")
    public R getTestById(Long testId) {
        try {
            MendaoTest mendaoTest = mendaoTestService.findOne(testId);

            MendaoTestResp testResp = new MendaoTestResp();
            testResp.setTestId(mendaoTest.getId());
            testResp.setTestName(mendaoTest.getName());
            testResp.setTestImage(mendaoTest.getImage());
            testResp.setTestDesc(mendaoTest.getTestDesc());
            testResp.setTestIntroduction(mendaoTest.getIntroduction());
            testResp.setStatus(mendaoTest.getStatus());

            return R.ok(testResp);
        } catch (Exception e) {
            log.error("获取测评异常", e);
            return R.error("发生异常");
        }
    }

    @GetMapping(value = "/getTopicByTestId")
    public R getTopicByTestId(Long testId) {
        try {
            List<MendaoTopicGroupResp> respList = new ArrayList<MendaoTopicGroupResp>();
            MendaoTest mendaoTest = mendaoTestService.findOne(testId);
            if (mendaoTest.getTopicGroup() != null && !"".equals(mendaoTest.getTopicGroup())) {
                respList = JSONObject.parseArray(mendaoTest.getTopicGroup(), MendaoTopicGroupResp.class);
            }
            return R.ok(respList);
        } catch (Exception e) {
            log.error("获取测评={}问题异常", testId, e);
            return R.error("发生异常");
        }
    }

    @RequestMapping(value = "/getTopicLibrary")
    public R getTopicLibrary(Long testId) {
        try {
            List<MendaoTopicLibraryResp> respList = new ArrayList<MendaoTopicLibraryResp>();
            List<MendaoTopicLibrary> list = topicLibraryService.getListByTestId(testId);
            if (list != null && list.size() > 0) {
                for (MendaoTopicLibrary test : list) {
                    MendaoTopicLibraryResp topicLibraryResp = new MendaoTopicLibraryResp();
                    topicLibraryResp.setTopicLibraryName(test.getTopicLibraryName());
                    topicLibraryResp.setTopicGroupId(test.getTopicGroupId());
                    topicLibraryResp.setOptions(test.getOptions());
                    respList.add(topicLibraryResp);
                }
            }
            return R.ok(respList);
        } catch (Exception e) {
            log.error("获取测评={}问题异常", testId, e);
            return R.error("发生异常");
        }
    }

    @GetMapping(value = "/getTestReport")
    public R getTestReport(Long testId) {
        try {
            List<MendaoTopicLibraryResp> respList = new ArrayList<MendaoTopicLibraryResp>();

            List<MendaoTestReport> list = testReportService.getListByTestId(testId);
            if (list != null && list.size() > 0) {
                MendaoTestReport report = list.get(0);
                return R.ok(report);
            }
            return R.ok("请求成功", null);
        } catch (Exception e) {
            log.error("获取测评={}问题异常", testId, e);
            return R.error("发生异常");
        }
    }

    /**
     * 提交测评信息
     *
     * @param mendaoTestReq
     * @return
     */
    @PostMapping({"/commitTest"})
    public Object commitTest(@RequestBody MendaoTestReq mendaoTestReq, HttpServletRequest request) {
        try {
            MendaoStu mendaoStu = new MendaoStu();
            mendaoStu.setTestId(mendaoTestReq.getTestId());
            mendaoStu.setStuName(mendaoTestReq.getStuName());
            mendaoStu.setSchoolName(mendaoTestReq.getSchoolName());
            mendaoStu.setPhone(mendaoTestReq.getPhone());
            if(Objects.isNull(mendaoTestReq.getStuId())){
                mendaoTestReq.setStuId(getStuId(request));
            }
            if(Objects.nonNull(mendaoTestReq.getStuId())){
                mendaoStu.setBindStuId("zj" + mendaoTestReq.getStuId());
            }

            mendaoStu.setList(JSONObject.toJSONString(mendaoTestReq.getList()));
            mendaoStu.setCreatedTime(new Date());
            this.mendaoStuService.insertDate(mendaoStu);

            Map<String, Object> map = new HashMap<>();
            map.put("testId", mendaoTestReq.getTestId());
            map.put("id", mendaoStu.getId());
            return R.ok(map);
        } catch (Exception e) {
            log.error("获取测评={}问题异常", mendaoTestReq, e);
            return R.error("发生异常");
        }
    }

    /**
     * 显示测评结果
     *
     * @param mendaoTestReq
     * @return
     */
    @PostMapping(value = "/showCommitTest")
    public R showCommitTest(@RequestBody MendaoTestReq mendaoTestReq) {

        BaseRespData resp = new BaseRespData();
        try {
            MendaoStu mendaoStu = this.mendaoStuService.findOne(mendaoTestReq.getId());
            List<TestTimu> testTimuList = JSONObject.parseArray(mendaoStu.getList(), TestTimu.class);
            mendaoTestReq.setList(testTimuList);

            if (mendaoTestReq.getList() != null && mendaoTestReq.getList().size() > 0) {
                List<TestTimu> list = mendaoTestReq.getList();
                Map<String, Integer> map = new HashMap<>();
                for (TestTimu timu : list) {
                    if (map.containsKey(timu.getTopicGroupId())) {
                        map.put(timu.getTopicGroupId(), map.get(timu.getTopicGroupId()) + timu.getScore());
                    } else {
                        map.put(timu.getTopicGroupId(), timu.getScore());
                    }
                }


                MendaoCommitResp commitResp = new MendaoCommitResp();
                commitResp.setCreatedTime(mendaoStu.getCreatedTime());

                List<MendaoTestReport> reportList = testReportService.getListByTestId(mendaoTestReq.getTestId());
                MendaoTest mendaoTest = mendaoTestService.findOne(mendaoTestReq.getTestId());

                if (reportList != null && reportList.size() > 0) {
                    MendaoTestReport report = reportList.get(0);

                    commitResp.setTestName(mendaoTest.getName());
                    commitResp.setIsShowReportDesc(report.getIsShowReportDesc());
                    if (report.getIsShowReportDesc() == 1) {
                        commitResp.setReportDesc(report.getReportDesc());
                    }else{
                        commitResp.setReportDesc(null);
                    }
                    //得分list
                    List<TableTestMsg> tableTestMsgList = new ArrayList<>();
                    //图标设置
                    commitResp.setIsShowTableSet(report.getIsShowTableSet());
                    if (report.getIsShowTableSet() == 1) {
                        MendaoTableSet mendaoTableSet = JSONObject.parseObject(report.getTableSet(), MendaoTableSet.class);
                        commitResp.setTableTitle(mendaoTableSet.getTableTitle());

                        MendaoTablesSetResp mendaoTablesSetResp = new MendaoTablesSetResp();
                        mendaoTablesSetResp.setTableName(mendaoTableSet.getTableName());
                        mendaoTablesSetResp.setTableColor(mendaoTableSet.getTableColor());

                        List<TopicGroup> topicGroupList = JSONObject.parseArray(mendaoTest.getTopicGroup(), TopicGroup.class);
                        for (TopicGroup topicGroup : topicGroupList) {
                            TableTestMsg tableTestMsg = new TableTestMsg();
                            tableTestMsg.setTopicGroupId(topicGroup.getTopicGroupId());
                            tableTestMsg.setTopicGroupCode(topicGroup.getTopicGroupCode());
                            tableTestMsg.setUnitName(topicGroup.getTopicGroupName());
                            tableTestMsg.setUnitScore(map.get(topicGroup.getTopicGroupId()) + "");

                            tableTestMsgList.add(tableTestMsg);
                        }

                        tableTestMsgList.sort(Comparator.comparingInt(x -> Integer.parseInt(x.getUnitScore())));
                        Collections.reverse(tableTestMsgList);
                        mendaoTablesSetResp.setTableTestMsg(tableTestMsgList);

                        commitResp.setTableSet(mendaoTablesSetResp);
                    }else{
                        commitResp.setTableSet(null);
                    }

                    //图标总结
                    commitResp.setIsShowTableResult(report.getIsShowTableResult());
                    if (report.getIsShowTableResult() == 1) {
                        MendaoTableResult tableResult = JSONObject.parseObject(report.getTableResult(), MendaoTableResult.class);

                        MendaoTableResultResp tableResultResp = new MendaoTableResultResp();
                        tableResultResp.setUpContent(tableResult.getUpDesc());
                        StringBuffer downContent = new StringBuffer();
                        for (int i = 0; i < tableResult.getTopNum(); i++) {
                            if (i == 0) {
                                downContent.append(tableTestMsgList.get(i).getUnitName());
                            } else {
                                downContent.append(tableResult.getSplitDesc());
                                downContent.append(tableTestMsgList.get(i).getUnitName());
                            }
                        }
                        tableResultResp.setDownContent(downContent.toString());

                        commitResp.setTableResult(tableResultResp);
                    }else{
                        commitResp.setTableResult(null);
                    }
                    //题组总结
                    commitResp.setIsShowTopicReportList(report.getIsShowTopicReportList());
                    if (report.getIsShowTopicReportList() == 1) {
                        MendaoTopicReport topicReport = JSONObject.parseObject(report.getTopicReport(), MendaoTopicReport.class);

                        MendaoTopicReportResp topicReportResp = new MendaoTopicReportResp();

                        topicReportResp.setTopicReportTitle(topicReport.getTitleWarning());

                        if (topicReport.getTopicReportList() != null && topicReport.getTopicReportList().size() > 0) {
                            List<TopicReport> topicReportBeanList = new ArrayList<>();
                            if (topicReport.getOrderType() == 1) {
                                List<TopicGroup> topicGroupList = JSONObject.parseArray(mendaoTest.getTopicGroup(), TopicGroup.class);
                                for (int i = 0; i < topicReport.getShowNum(); i++) {
                                    TopicReport topicReportBean = new TopicReport();

                                    int score = map.get(topicGroupList.get(i).getTopicGroupId());
                                    for (MendaoTopicReportList topicReportList : topicReport.getTopicReportList()) {
                                        if (topicReportList.getTopicGroupId().equals(topicGroupList.get(i).getTopicGroupId())) {
                                            topicReportBean.setTitle(topicReportList.getTitle());
                                            for (MendaoSocreReport socreReport : topicReportList.getSocreReport()) {
                                                if (score >= socreReport.getTopSocre() && score <= socreReport.getDownSocre()) {
                                                    topicReportBean.setContent(socreReport.getSocreDesc());
                                                    break;
                                                }
                                            }
                                            topicReportBeanList.add(topicReportBean);
                                            break;
                                        }
                                    }
                                }
                            } else {
                                for (int i = 0; i < topicReport.getShowNum(); i++) {

                                    TopicReport topicReportBean = new TopicReport();
                                    int score = map.get(tableTestMsgList.get(i).getTopicGroupId());
                                    for (MendaoTopicReportList topicReportList : topicReport.getTopicReportList()) {
                                        if (topicReportList.getTopicGroupId().equals(tableTestMsgList.get(i).getTopicGroupId())) {
                                            topicReportBean.setTitle(topicReportList.getTitle());
                                            for (MendaoSocreReport socreReport : topicReportList.getSocreReport()) {
                                                if (score > socreReport.getTopSocre() && score < socreReport.getDownSocre()) {
                                                    topicReportBean.setContent(socreReport.getSocreDesc());
                                                    break;
                                                }
                                            }
                                            topicReportBeanList.add(topicReportBean);
                                            break;
                                        }
                                    }
                                }
                            }

                            topicReportResp.setTopicReportList(topicReportBeanList);
                        }
                        commitResp.setTopicReport(topicReportResp);
                    }else{
                        commitResp.setTopicReport(null);
                    }
                    //更多建议
                    commitResp.setIsShowMoreSuggest(report.getIsShowMoreSuggest());
                    if (report.getIsShowMoreSuggest() == 1) {
                        commitResp.setMoreSuggestTitle(report.getMoreSuggestTitle());

                        List<TopicReport> moreSuggestRespList = new ArrayList<>();

                        List<MendaoMoreSuggest> moreSuggestList = JSONObject.parseArray(report.getMoreSuggest(), MendaoMoreSuggest.class);

                        for (MendaoMoreSuggest moreSuggest : moreSuggestList) {
                            int length = moreSuggest.getSuggestCode().length();
                            StringBuffer codeString = new StringBuffer();
                            for (int i = 0; i < length; i++) {
                                codeString.append(tableTestMsgList.get(i).getTopicGroupCode());
                            }
                            if (moreSuggest.getSuggestCode().equals(codeString.toString())) {
                                for (MendaoSuggestArray array : moreSuggest.getSuggestArray()) {
                                    TopicReport moreSuggestResp = new TopicReport();
                                    moreSuggestResp.setTitle(array.getSuggestTitle());
                                    moreSuggestResp.setContent(array.getSuggestContent());
                                    moreSuggestRespList.add(moreSuggestResp);
                                }
                            }
                        }

                        commitResp.setMoreSuggest(moreSuggestRespList);
                    }else{
                        commitResp.setMoreSuggest(null);
                    }

                    //测评总结
                    commitResp.setIsShowReportResult(report.getIsShowReportResult());
                    if (report.getIsShowReportResult() == 1) {
                        commitResp.setReportResult(report.getReportResult());
                    }else {
                        commitResp.setReportResult(null);
                    }

                    //测试尾图
                    commitResp.setIsShowLastImage(report.getIsShowLastImage());
                    if (report.getIsShowLastImage() == 1) {
                        commitResp.setLastImage(report.getLastImage());
                    }else {
                        commitResp.setLastImage(null);
                    }
                    return R.ok(commitResp);
                }
                return R.error("未查询到测评结果设置");
            } else {
                return R.error("参数为空");
            }
        } catch (Exception e) {
            log.error("显示测评结果={}问题异常", mendaoTestReq, e);
            return R.error("发生异常");
        }
    }

    /**
     * 获取我的测评
     * @param stuId
     * @return
     */
    @GetMapping("/getMyTest")
    public R getMyTest(String stuId) {
        List<MendaoStu> list = mendaoStuService.selectByStuId("zj"+stuId);
        return R.ok(list);
    }
}
